import { useCookies } from "@vueuse/integrations/useCookies";

type UserPayload = ReqPayLoad<UserType>;
// eslint-disable-next-line ts/consistent-type-definitions
type UserGetter = {
  isLogin: (store: UserPayload) => boolean;
}
interface UserAction {
  setPhone: (phone: string) => void;
  setEmail: (email: string) => void;
  setPassWord: (password: string) => void;
  setUser: (user: UserType) => void;
  logout: () => void;
  /**
   * @description should be private
   */
  updateTime: () => void;
}
export const useMyUserStore = defineStore<
  "myUserStore",
  UserPayload,
  UserGetter,
  UserAction
          >({
            id: "myUserStore",
            state: () => ({
              data: {
                email: "",
                phone: "",
                id: 0,
                password: "",
                nickname: "",
                sex: "未知",
                desc: "",
                status: 0, // 0 下线 1 在线
                created_time: Date.now(),
                updated_time: Date.now(),
              },
            }),
            getters: {
              isLogin: (store) => {
                return store.data.id !== 0 && store.data.status === 1;
              },
            },
            actions: {
              updateTime() {
                this.data.updated_time = Date.now();
              },
              setPhone(phone: string) {
                this.data.phone = phone;
                this.updateTime()
              },
              setEmail(email: string) {
                this.data.email = email;
                this.updateTime()
              },
              setPassWord(password: string) {
                this.data.password = password;
                this.updateTime()
              },
              setUser(user: UserType) {
                this.data = user;
                this.updateTime()
              },
              logout() {
                this.data = {
                  email: "",
                  phone: "",
                  id: 0, // 0 为未登录
                  nickname: "",
                  password: "",
                  // avatar: "",//暂时砍掉
                  sex: "未知",
                  desc: "",
                  status: 0, // 0 下线 1 启用
                  created_time: Date.now(),
                  updated_time: Date.now(),
                };
                const cookie = useCookies(["Authorization"]);
                cookie.set("Authorization", "", { maxAge: 0 });
              },
            },
            persist: {
              storage: persistedState.sessionStorage,
            },
          });
